package com.eazyshop.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.eazyshop.canal.config.RabbitMQConfig;
import com.eazyshop.canal.utils.CanalUtil;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@CanalEventListener
public class GoodsListener {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 监控sku数据库发生变化
     * 商品上架
     * @param eventType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsPutOnTheShelf(CanalEntry.EventType eventType, CanalEntry.RowData rowData){

        // 获得改变以后的数据
        Map<String, String> afterMap = CanalUtil.convertToMap(rowData.getAfterColumnsList());
        // 获得改变之前的数据
        Map<String, String> beforeMap = CanalUtil.convertToMap(rowData.getBeforeColumnsList());
        // 获得最新上架的商品
        // 在改变之前上架状态是0 改变以后上架状态是1

        if("0".equals(beforeMap.get("is_marketable"))&&"1".equals(afterMap.get("is_marketable"))){
            // spu。id发送消息给mq

            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",afterMap.get("id"));

        }
        //商品下架监控
        /**
         * spu表中在改变之前状态是1下架以后状态是0
         */
        if("0".equals(afterMap.get("is_marketable"))&&"1".equals(beforeMap.get("is_marketable"))){
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_OFF_EXCHANGE,"",afterMap.get("id"));
        }

    }

}
